<?php
	$foto  = $_GET["foto"];
	
	$w = $_GET["w"];
	$h = $_GET["h"];
	$fx = $_GET["fx"];
	$fy = $_GET["fy"];
	
	$filename = "public/$foto";
	
	if(!file_exists($filename)){
		$filename="public/semfoto.png";
	}
	
	$width = $w;
	$height = $h;
	$fix_x = $fx;
	$fix_y = $fy;

	$tn = explode(".", $foto);
	$THUMB_NAME = $tn[0]."_".$fx."x".$fy.".".$tn[1];
	
	$info = getimagesize($filename);
	$mime = $info['mime'];
	
	header('Content-type: image/jpeg');

	if(file_exists("public/thumb_cache/".$THUMB_NAME)){
		readfile("public/thumb_cache/".$THUMB_NAME);
	}else{
		// Get new dimensions
		$width_orig = $info[0];
		$height_orig = $info[1];

		//list($width_orig, $height_orig) = getimagesize($filename);
		
		$ratio_orig = $width_orig / $height_orig;
		if($width/$height > $ratio_orig) 
		   $width = $height*$ratio_orig;
		else
			$height = $width/$ratio_orig;
		$x_pos = ($width-$fix_x) / 2;
		$y_pos = ($height-$fix_y) / 2;
		
		// Resample
		$image_p = imagecreatetruecolor($fix_x, $fix_y);
		$bgc  = imagecolorallocate($image_p, 255, 255, 255); // bg branco
		#$bgc  = imagecolorallocate($image_p,0,0,0); // bg preto
		imagefilledrectangle($image_p, 0, 0, $fix_x, $fix_y, $bgc);

		if ($mime == "image/png"){
			$image = imagecreatefrompng($filename);	
		}else{
			$image = imagecreatefromjpeg($filename);
		}
				
		imagecopyresampled($image_p, $image, -$x_pos, -$y_pos, 0, 0, $width, $height, $width_orig, $height_orig);
		// Output
		imagejpeg($image_p, "public/thumb_cache/".$THUMB_NAME);
		imagedestroy($image_p);
		readfile("public/thumb_cache/".$THUMB_NAME);
	}
?>